﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace B2BToolKitControl
{

    public class B2BReceivedDataDetector
    {
        public enum ReceivedDataType
        {
            None,
            B2BToolKit_Responds,
            BatteryPack_Responds
        }
        public struct ReceivedPacket
        {
            public ReceivedDataType Type;
            public byte Cmd;
            public byte[] Data;
        }

        List<byte> rawData;
        public B2BReceivedDataDetector()
        {
            rawData = new List<byte>();
        }
        public List<ReceivedPacket> DataDetector(byte[] appendRawData)
        {
            List<ReceivedPacket> detectorData = new List<ReceivedPacket>();
            byte respondCmd;
            byte[] receivedData;

            bool detectFlag = false;
            bool uartFound = false;
            int segStartIdxOfRawData = 0;
            int segEndIdxOfRawData = 0;
            ReceivedPacket packet;

            rawData.AddRange(appendRawData);

            do
            {
                detectFlag = false;
                uartFound = LEVUtilityLibrary.B2BToolKit_USBPacketFormat.Unpacking(
                            rawData.ToArray<byte>(),
                            out respondCmd,
                            out receivedData,
                            out segStartIdxOfRawData, 
                            out segEndIdxOfRawData);
                if (uartFound)
                {
                    packet.Cmd = respondCmd;
                    packet.Data = receivedData;
                    if((respondCmd == (byte)B2BCommandProvider.Cmd_DataTransmit.Cmd_UART_Receive_Data) ||
                        (respondCmd == (byte)B2BCommandProvider.Cmd_DataTransmit.Cmd_One_Wire_Receive_Data))
                    {
                        packet.Type = ReceivedDataType.BatteryPack_Responds;
                        detectorData.Add(packet);
                        rawData.RemoveRange(0, segEndIdxOfRawData + 1);
                    }
                    else
                    {
                        packet.Type = ReceivedDataType.B2BToolKit_Responds;
                        detectorData.Add(packet);
                        rawData.RemoveRange(segStartIdxOfRawData, segEndIdxOfRawData - segStartIdxOfRawData + 1);
                    }

                    detectFlag = true;
                }
            } while (detectFlag);

            return detectorData;
        }
    }//public class B2BReceivedDataDetector
}//namespace B2BToolKitControl

